home *** CD-ROM | disk | FTP | other *** search
/ Shareware Grab Bag / Shareware Grab Bag.iso / 090 / pctj0987.arc / NODES.CXX < prev    next >
Text File  |  1987-02-18  |  2KB  |  92 lines

  1.  
  2. class   node
  3. {
  4.         virtual ~node(){}
  5. public:
  6.           node(){}
  7.     virtual int    val();         // evaluate node
  8.     virtual void     print();        // pretty print node
  9. };
  10.  
  11. int node::val()
  12. {
  13.      printf("error"); return 0;
  14. }
  15.  
  16. void node::print()
  17. {
  18.      printf("%d",val());        // sensible default
  19. }
  20.  
  21.  
  22. class   node_int : public node            // integer node
  23. {
  24.     int i;
  25. public:
  26.     node_int( int j ) : i(j) {}
  27.     int    val() {   return i; }
  28. };
  29.  
  30. class   node_bop : public node         // binary op node
  31. {
  32.     node *l, *r;
  33. public:
  34.        ~node_bop(){ delete l; delete r; }
  35.     node_bop( node  * ll, node  * rr) : l(ll), r(rr) {}
  36.     int    val();
  37.     void     print();
  38.  
  39.     virtual int   ofn(int l, int r);// binary op function
  40.     virtual void  osm();        // binary op symbol print
  41. };
  42.  
  43. int node_bop::val()
  44. {    
  45.     return ofn( l->val(), r->val() );
  46. }
  47.  
  48. void node_bop::print()
  49. {
  50.     printf("(");        l->print();
  51.     osm();            r->print();
  52.     printf("=%d)",        val());
  53. }
  54.  
  55. void node_bop::osm()
  56. {
  57.      printf("error");              // shouldn't happen
  58. }
  59.  
  60. int node_bop::ofn( int, int)
  61. {
  62.      printf("error"); return 0;    // shouldn't happen
  63. }
  64.  
  65. class   node_sub : public node_bop         // subtraction node
  66. {
  67. public:
  68.     node_sub( node * ll, node * rr) : ( ll, rr ) {}
  69.     int    ofn(int l, int r){ return l-r; }
  70.     void     osm(){  printf("-"); }
  71. };
  72.  
  73. class   node_mul : public node_bop         // multiplication node
  74. {
  75. public:
  76.     node_mul( node * ll, node * rr) : ( ll, rr ) {}
  77.     int    ofn(int l, int r){ return l*r; }
  78.     void     osm(){  printf("*"); }
  79. };
  80.  
  81. main()
  82. {
  83.      node * n1 = new node_int(5),
  84.       * n2 = new node_int(7),
  85.       * n3 = new node_sub(n1,n2),
  86.       * n4 = new node_int(10),
  87.       * n5 = new node_mul(n4,n3);
  88.     n5->print();
  89.     delete n5;
  90. }
  91.  
  92.